import { LOADING_SPURCE_CODE, NOT_BOOTSTRAPPED} from "../applications/app.helper";

/** 将加载函数返回的bootstrap，mount，unmount方法挂载到app上 */
export async function toLoadPromise(app){
  if(app.loadPromise){
    return app.loadPromise
  }
  return (app.loadPromise = Promise.resolve().then(async()=>{
    app.status = LOADING_SPURCE_CODE;
    const { bootstrap, mount, unmount } = await app.loadApp(app.customProps)
    app.status = NOT_BOOTSTRAPPED
    app.bootstrap = flattenFnArray(bootstrap)
    app.mount = flattenFnArray(mount)
    app.unmount = flattenFnArray(unmount)
    delete app.loadPromise
    return app
  }))
  
}

function flattenFnArray(fns){
  fns = Array.isArray(fns) ? fns: [fns]
  return (props)=> fns.reduce((p,fn)=>p.then(()=>fn(props)),Promise.resolve())
}